import { Form, message } from 'ant-design-vue'
import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree'
import { isEmpty } from 'lodash-es'
import { type Ref, createVNode, ref, watch } from 'vue'

import { materialApi } from '@/apis'
import { GroupItem } from '@/apis/materialTypes'
import { useDialog } from '@/hooks'

import type { SearchParams } from '../types'

type Params = {
  searchParams: Ref<SearchParams>
  handleGetVideoList: PromiseFunc
}

const { useForm } = Form

export function useGroup({ searchParams, handleGetVideoList }: Params) {
  const groupData = ref([] as GroupItem[])
  const groupDataList = ref([] as TreeDataItem[])
  const autoExpandParent = ref(false)
  const selectedGroupKeys = ref([] as string[])
  const expandedGroupKeys = ref([] as string[])
  const searchGroupValue = ref('')
  const selectedGroup = ref({} as TreeDataItem)
  const showSubGroup = ref(false)
  const showRename = ref(false)
  const subGroupFormModel = ref({
    id: '',
    name: ''
  })
  const renameFormModel = ref({
    id: '',
    name: ''
  })
  const groupFormRules = ref({
    name: [{ required: true, max: 12, message: '请输入' }]
  } as FormRules)
  const getGroupListLoading = ref(false)
  const addSubGroupLoading = ref(false)
  const renameSubGroupLoading = ref(false)

  const subGroupFormRef = useForm(subGroupFormModel, groupFormRules)

  const renameFormRef = useForm(renameFormModel, groupFormRules)

  const { showConfirm } = useDialog()

  /** 获取数据列表 */
  function getDataList(arr: GroupItem[]) {
    for (let i = 0; i < arr.length; i++) {
      const node = arr[i]
      const key = node.key
      const title = node.title
      groupDataList.value.push({ key, title })
      if (node.children.length > 0) {
        getDataList(node.children)
      }
    }
  }

  /** 获取父级Key */
  function getParentKey(key: string | number, tree: GroupItem[]) {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.children.length) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children)
        }
      }
    }
    return parentKey
  }

  /** 获取分组标题 */
  function getGroupTitle(node: TreeDataItem) {
    if (node.key === 1 || node.children) {
      return `${node.title}(${node.videoNum})`
    }

    const title = node.title!

    if (title.indexOf(searchGroupValue.value) > -1) {
      return createVNode('span', null, [
        title.substring(0, title.indexOf(searchGroupValue.value)),
        createVNode('span', { style: 'color: #f50' }, searchGroupValue.value),
        title.substring(
          title.indexOf(searchGroupValue.value) + searchGroupValue.value.length
        )
      ])
    }
    return node.title
  }

  /** 选择分组 */
  function handleSelectGroup(v: any, e: any) {
    selectedGroup.value = e.node
  }

  /** 展开 */
  function handleExpandGroup(keys: string[]) {
    expandedGroupKeys.value = keys
    autoExpandParent.value = false
  }

  /** 搜索分组 */
  function handleSearchGroup(value: string) {
    const expanded = groupDataList.value
      .map((item: TreeDataItem) => {
        if ((item.title as string).indexOf(value) > -1) {
          return getParentKey(item.key as string, groupData.value)
        }
        return null
      })
      .filter((item, i, self) => item && self.indexOf(item) === i)

    if (expanded.length > 0) {
      expanded.unshift(0)
    }

    expandedGroupKeys.value = expanded as string[]
    searchGroupValue.value = value
    autoExpandParent.value = true
  }

  /** 显示子分组弹窗 */
  function handleShowSubGroup() {
    if (isEmpty(selectedGroup.value)) {
      message.warn('请选择分组', 1.5)
      return
    }

    if (selectedGroup.value.pos.split('-').length > 3) {
      message.warn('最大支持3级', 1.5)
      return
    }

    showSubGroup.value = true
  }

  /** 关闭子分组弹窗 */
  function handleCloseSubGroup() {
    subGroupFormRef.resetFields()
    addSubGroupLoading.value = false
    showSubGroup.value = false
  }

  /** 添加子分组 */
  function addSubGroup() {
    subGroupFormRef
      .validate()
      .then(async () => {
        try {
          addSubGroupLoading.value = true
          subGroupFormModel.value.id = selectedGroup.value.eventKey as any
          await materialApi.createGroup(subGroupFormModel.value)

          showSubGroup.value = false
          subGroupFormRef.resetFields()
          await handleGetGroupList()
        } finally {
          addSubGroupLoading.value = false
        }
      })
      .catch(() => {})
  }

  /** 显示重命名弹窗 */
  function handleShowRenameGroup() {
    if (isEmpty(selectedGroup.value)) {
      message.warn('请选择分组', 1.5)
      return
    }

    if (selectedGroup.value.eventKey === 1) {
      message.warn('根节点分组无法重命名', 1.5)
      return
    }

    if (selectedGroup.value.eventKey === 2) {
      message.warn('默认分组无法重命名', 1.5)
      return
    }

    renameFormModel.value.name = selectedGroup.value.dataRef.title
    showRename.value = true
  }

  /** 关闭重命名弹窗 */
  function handleCloseRenameGroup() {
    renameFormRef.resetFields()
    renameSubGroupLoading.value = false
    showRename.value = false
  }

  /** 重命名 */
  function renameGroup() {
    renameFormRef
      .validate()
      .then(async () => {
        try {
          renameSubGroupLoading.value = true
          renameFormModel.value.id = selectedGroup.value.eventKey as any
          await materialApi.renameGroup(renameFormModel.value)

          showRename.value = false
          renameFormRef.resetFields()
          await handleGetGroupList()
        } finally {
          renameSubGroupLoading.value = false
        }
      })
      .catch(() => {})
  }

  /** 删除分组 */
  function handleDeleteGroup() {
    if (isEmpty(selectedGroup.value)) {
      message.warn('请选择分组', 1.5)
      return
    }

    if (selectedGroup.value.eventKey === 1) {
      message.warn('根节点分组无法删除', 1.5)
      return
    }

    if (selectedGroup.value.eventKey === 2) {
      message.warn('默认分组无法删除', 1.5)
      return
    }

    if (
      selectedGroup.value.children &&
      selectedGroup.value.children.length > 0
    ) {
      message.warn('当前分组下有子分组，无法删除', 1.5)
      return
    }

    showConfirm({
      content: '确认删除分组？',
      onOk: async () => {
        try {
          await materialApi.deleteGroup(selectedGroup.value.eventKey)
          handleGetGroupList()
        } catch (error) {}
      }
    })
  }

  /** 获取分组列表 */
  async function handleGetGroupList() {
    searchGroupValue.value = ''
    selectedGroup.value = {}
    selectedGroupKeys.value = []

    try {
      getGroupListLoading.value = true
      groupData.value = await materialApi.getGroupList()
    } finally {
      getGroupListLoading.value = false
    }
  }

  watch(groupData, val => {
    getDataList(val)
    handleSearchGroup('')
  })

  watch(selectedGroup, val => {
    searchParams.value.groupId = val.eventKey
    handleGetVideoList()
  })

  return {
    groupData,
    expandedGroupKeys,
    selectedGroupKeys,
    autoExpandParent,
    selectedGroup,
    searchGroupValue,
    showSubGroup,
    subGroupFormRef,
    subGroupFormModel,
    showRename,
    renameFormRef,
    renameFormModel,
    renameSubGroupLoading,
    getGroupListLoading,
    addSubGroupLoading,
    getGroupTitle,
    handleExpandGroup,
    handleSelectGroup,
    handleSearchGroup,
    handleShowSubGroup,
    handleCloseSubGroup,
    addSubGroup,
    handleShowRenameGroup,
    handleCloseRenameGroup,
    renameGroup,
    handleDeleteGroup,
    handleGetGroupList
  }
}
